﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.Api.Application.hqApplication.Commands.PigBabyss;
using RearLivestock.RBAC.Api.Application.wbxApplication.Commands.Role;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.Application.hqApplication.Commands.Enterprisess
{
    public class ShowEnterpricesHandler : IRequestHandler<ShowEnterpriceCommand, Result<PageResultDto<Enterprise>>>
    {
        private readonly IMapper mapper;

        private readonly IBaseRepository<Enterprise> EnterpriseRepository;

        public ShowEnterpricesHandler(IMapper mapper, IBaseRepository<Enterprise> EnterpriseRepository)
        {
            this.mapper = mapper;
            this.EnterpriseRepository = EnterpriseRepository;
        }
        /// <summary>
        /// 企业显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result<PageResultDto<Enterprise>>> Handle(ShowEnterpriceCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<PageResultDto<Enterprise>>() { Code = (int)CommonErrorCode.Search };
            var page = new PageResultDto<Enterprise>() { List = new List<Enterprise>(), PageCount = 0, TotalCount = 0 };
            var res = await (await EnterpriseRepository.GetAll()).ToListAsync();
            page.TotalCount = res.Count();
            page.PageCount = (int)Math.Ceiling(page.TotalCount * 1.0 / request.PageSize);
            page.List = res.OrderBy(x => x.EnterpriseId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
            result.Data = page;
            result.Code = (int)CommonErrorCode.Success;
            return result;
        }

      
    }
}
